/**  
 * @Title:  DelayDataSourceConfiguration.java   
 * @Package com.platform.config   
 * @Description: (用一句话描述该文件做什么)   
 * @author: <a href="mailto:15909910367@163.com">吴先生</a> 
 * @date:   2020年9月2日 上午6:20:56   
 * @version V1.0 
 * @Copyright: 2020 吴先生.
 */
package com.platform.config;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.jdbc.support.JdbcUtils;

import com.platform.utils.SpringContextUtil;

/**   
 * @ClassName:  DelayDataSourceConfiguration   
 * @Description:延迟加载数据源-程序启动完成后加载
 * @author: <a href="mailto:15909910367@163.com">吴先生</a>  
 * @date:   2020年9月2日 上午6:20:56   
 *     
 * @Copyright: 2020 吴元森.  
 */
public class DelayDataSourceConfiguration implements ApplicationListener<ApplicationStartedEvent>{
	
	private Logger log = LoggerFactory.getLogger(DelayDataSourceConfiguration.class);
	
	private static final String SEARCHDBLINKSQL = "select databasetype,defaultschema,ipaddress,password,portnumber,usename,driverClassName,userName,title from sys_databases where disabled=1";//usename=? and
	
    @Override
	public void onApplicationEvent(ApplicationStartedEvent event) {
    	log.info("\n----------------------------------------------------------\n\t" +
                "系统启动成功: \t\t开始加载第三方数据源\n" +
                "----------------------------------------------------------");
    	ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext)SpringContextUtil.getApplicationContext();
    	DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory)applicationContext.getBeanFactory();
    	DataSource dataSource = (DataSource)beanFactory.getBean("master");
    	List<com.platform.ext.datasource.DataSource> datasourceList = new ArrayList<com.platform.ext.datasource.DataSource>();
    	if(dataSource != null) {
	    	try {
				Connection conn = dataSource.getConnection();
				PreparedStatement pstmt = conn.prepareStatement(SEARCHDBLINKSQL);
				ResultSet rs = pstmt.executeQuery();
				while(rs.next()) {
					String db_databasetype = rs.getString(1);
					if(db_databasetype.equalsIgnoreCase("FTP")) {
						break;
					}
					String db_defaultschema = rs.getString(2);
					String db_ipaddress = rs.getString(3);
					String db_password = rs.getString(4);
					int db_portnumber = rs.getInt(5);
					String db_usename = rs.getString(6);
					String db_driverClassName = rs.getString(7);
					String db_userName = rs.getString(8);
					com.platform.ext.datasource.DataSource ds = new com.platform.ext.datasource.DataSource();
					ds.setDsName(db_usename);
					ds.setDsDrivername(db_driverClassName);
					ds.setDsUrl(createDBLinkStr(db_databasetype, db_ipaddress, db_portnumber, db_defaultschema));
					ds.setDsType(db_databasetype);
					ds.setDsUsername(db_userName);
					ds.setDsPassword(db_password);
					ds.setRemarks(rs.getString(9));;
					datasourceList.add(ds);
				}
				com.platform.ext.datasource.DataSourceManager.add2BeanFactory(datasourceList);
				JdbcUtils.closeResultSet(rs);
				JdbcUtils.closeStatement(pstmt);
				JdbcUtils.closeConnection(conn);
			} catch (Exception e) {
				e.printStackTrace();
			}
    	}else {
    		log.info("获取master节点失败");
    	}
    	
	}
	
	/**
	 * @Title: createDBLinkStr   
	 * @Description: 构建数据库连接字符串
	 * @param dbType		数据库类型
	 * @param ipaddress		IP地址
	 * @param portnumber	连接端口号
	 * @param defaultschema	默认schema（库名称）
	 * @return      
	 * String	数据库连接字符串
	 */
	private static String createDBLinkStr(String dbType,String ipaddress,int portnumber,String defaultschema){
		StringBuilder dbLinkStr = new StringBuilder();
		switch(dbType.toLowerCase()) {
			case "mysql":
				dbLinkStr.append("jdbc:mysql://");
				dbLinkStr.append(ipaddress);
				dbLinkStr.append(":");
				dbLinkStr.append(portnumber);
				dbLinkStr.append("/");
				dbLinkStr.append(defaultschema);
				dbLinkStr.append("?useUnicode=true&characterEncoding=utf-8");
				break;
			case "oracle":
				dbLinkStr.append("jdbc:oracle:thin:@");
				dbLinkStr.append(ipaddress);
				dbLinkStr.append(":");
				dbLinkStr.append(portnumber);
				dbLinkStr.append(":");
				dbLinkStr.append(defaultschema);
				break;
			case  "sqlserver":
				dbLinkStr.append("jdbc:sqlserver://");
				dbLinkStr.append(ipaddress);
				dbLinkStr.append(":");
				dbLinkStr.append(portnumber);
				dbLinkStr.append(";DatabaseName=");
				dbLinkStr.append(defaultschema);
				break;
			case  "sybase":
				dbLinkStr.append("jdbc:sybase:Tds://");
				dbLinkStr.append(ipaddress);
				dbLinkStr.append(":");
				dbLinkStr.append(portnumber);
				dbLinkStr.append("/");
				dbLinkStr.append(defaultschema);
				break;
			case  "db2":
				dbLinkStr.append("jdbc:db2://");
				dbLinkStr.append(ipaddress);
				dbLinkStr.append(":");
				dbLinkStr.append(portnumber);
				dbLinkStr.append("/");
				dbLinkStr.append(defaultschema);
				break;
			case  "sqlite":
				break;
			case  "postgresql":
				dbLinkStr.append("jdbc:postgresql://");
				dbLinkStr.append(ipaddress);
				dbLinkStr.append(":");
				dbLinkStr.append(portnumber);
				dbLinkStr.append("/");
				dbLinkStr.append(defaultschema);
				break;
			case  "mongodb":
				break;
			case  "redis":
				break;

		}
		return dbLinkStr.toString();
	}
}
